package com.example.quartz.component;

import com.example.quartz.constant.QuartzConstants;
import com.example.quartz.module.sms.QuartzTask;
import com.example.quartz.module.sms.QuartzTaskLog;
import com.example.quartz.provider.sms.mapper.QuartzTaskLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author: wlp
 * @description: 描述：定时任务处理
 * @projectName: ScheduleJob
 * @date: 2019/10/12
 * @version: V1.0.0
 */
@Slf4j
@Component
public class MyScheduleJob extends QuartzJobBean {

    private final ThreadLocal<ExecutorService> service = ThreadLocal.withInitial(Executors::newSingleThreadExecutor);

    @Resource
    private QuartzTaskLogMapper quartzTaskLogMapper;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        QuartzTask quartzTask = (QuartzTask) context.getMergedJobDataMap().get(QuartzConstants.QUARTZ_PARAM_KEY);
        //任务开始时间
        long startTime = System.currentTimeMillis();
        QuartzTaskLog quartzTaskLog = QuartzTaskLog.builder()
                .quartzId(quartzTask.getId())
                .targetBean(quartzTask.getTargetBean())
                .targetMethod(quartzTask.getTargetMethod())
                .params(quartzTask.getParams())
                .quartzName("执行定时任务【" + quartzTask.getQuartzName() + "】")
                .quartzStatus(0)
                .build();
        quartzTaskLog.setCreateUserId(1L);
        quartzTaskLog.setCreateTime(new Date());
        try {
            ScheduleRunnable task = new ScheduleRunnable(quartzTask.getTargetBean(), quartzTask.getTargetMethod(), quartzTask.getParams(), quartzTask.getQuartzType(), quartzTask.getTargetContent());
            Future<?> future = service.get().submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;
            quartzTaskLog.setExecutionTime(times);
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + quartzTask.getId(), e);
            long times = System.currentTimeMillis() - startTime;
            quartzTaskLog.setExecutionTime(times);
            quartzTaskLog.setErrorInfo("任务执行完毕，任务ID：" + quartzTask.getId() + "， 总共耗时：" + times + "毫秒");
            quartzTaskLog.setQuartzStatus(1);
            quartzTaskLog.setErrorInfo("任务执行失败，任务ID：" + quartzTask.getId() + "===>>" + e.getMessage());
        } finally {
            quartzTaskLogMapper.insert(quartzTaskLog);
        }
    }
}
